import React from 'react';
import * as echarts from 'echarts/core';
import { BarChart, LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  CanvasRenderer
]);

class EChartsComponent extends React.Component {
  chartRef = React.createRef();
  chartInstance = null;

  // 初始化图表
  initChart = () => {
    // 确保DOM元素存在
    if (!this.chartRef.current) return;
    
    // 销毁现有实例（如果有）
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    
    // 初始化新实例
    this.chartInstance = echarts.init(
      this.chartRef.current,
      this.props.theme,  // 可选主题
      this.props.initOptions // 可选初始化配置
    );
    
    // 设置图表配置
    this.updateChart();
    
    // 绑定事件
    this.bindEvents();
  };

  // 更新图表配置
  updateChart = () => {
    if (!this.chartInstance || !this.props.option) return;
    
    // 使用notMerge可以完全替换旧配置
    this.chartInstance.setOption(
      this.props.option,
      this.props.notMerge || false,
      this.props.lazyUpdate || false
    );
    
    // 如果需要，立即执行布局和渲染
    if (this.props.autoResize) {
      this.chartInstance.resize();
    }
  };

  // 绑定事件
  bindEvents = () => {
    if (!this.chartInstance) return;
    
    // 解绑旧事件
    this.chartInstance.off();
    
    // 绑定新事件
    if (this.props.onEvents) {
      Object.keys(this.props.onEvents).forEach(eventName => {
        this.chartInstance.on(eventName, this.props.onEvents[eventName]);
      });
    }
  };

  // 响应式调整
  resizeChart = () => {
    if (this.chartInstance && this.props.autoResize !== false) {
      this.chartInstance.resize();
    }
  };

  // 生命周期方法
  componentDidMount() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
  }

  componentDidUpdate(prevProps) {
    // 当option或theme变化时更新图表
    if (
      this.props.option !== prevProps.option ||
      this.props.theme !== prevProps.theme ||
      this.props.onEvents !== prevProps.onEvents
    ) {
      this.updateChart();
      this.bindEvents();
    }
    
    // 如果initOptions变化，需要重新初始化
    if (this.props.initOptions !== prevProps.initOptions) {
      this.initChart();
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resizeChart);
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
  }

  render() {
    const { style, className } = this.props;
    const defaultStyle = { width: '890px', height: '550px' };
    
    return (
      <div
        ref={this.chartRef}
        style={{ ...defaultStyle, ...style }}
        className={className}
      />
    );
  }
}

// 默认props
EChartsComponent.defaultProps = {
  autoResize: true,
  notMerge: false,
  lazyUpdate: false
};

export default EChartsComponent;